package cn.zmwh.im.server.netty.processor;

import cn.zmwh.im.server.constant.BsKImConstant;
import cn.zmwh.im.server.constant.IMCmdConstants;
import cn.zmwh.im.server.constant.IMRedisKey;
import cn.zmwh.im.server.mq.dto.IMInfo;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@RequiredArgsConstructor
@Component("heartbeatProcessor")
public class ProcessorHeartbeat implements ImMessageProcessor {

    private final RedisTemplate redisTemplate;

    @Override
    public IMInfo read(ChannelHandlerContext ctx, IMInfo sendInfo) {
//        // 响应ws
        IMInfo<Object> result = new IMInfo<>();
        result.setCmd(IMCmdConstants.HEART_BEAT);
        //ctx.channel().writeAndFlush(result);
        // 设置属性
        AttributeKey<Long> heartBeatAttr = AttributeKey.valueOf(BsKImConstant.CHANNEL_ATTR_KEY.HEARTBEAT_TIMES);
        Long heartbeatTimes = ctx.channel().attr(heartBeatAttr).get();
        ctx.channel().attr(heartBeatAttr).set(++heartbeatTimes);
        if (heartbeatTimes % 10 == 0) {
            // 每心跳10次，用户在线状态续一次命
            AttributeKey<Long> userIdAttr = AttributeKey.valueOf(BsKImConstant.CHANNEL_ATTR_KEY.USER_ID);
            Long uid = ctx.channel().attr(userIdAttr).get();
            AttributeKey<String> terminalAttr = AttributeKey.valueOf(BsKImConstant.CHANNEL_ATTR_KEY.TERMINAL_TYPE);
            String terminal = ctx.channel().attr(terminalAttr).get();
            String key = String.join(":", IMRedisKey.GAIN_SERVER_ID, uid.toString(), terminal.toString());
            redisTemplate.expire(key, BsKImConstant.ONLINE_TIMEOUT_SECOND, TimeUnit.SECONDS);
        }
        AttributeKey<Long> userIdAttr = AttributeKey.valueOf(BsKImConstant.CHANNEL_ATTR_KEY.USER_ID);
        Long uid = ctx.channel().attr(userIdAttr).get();
        log.debug("心跳,userId:{},{}", uid, ctx.channel().id().asLongText());
        return result;
    }

}
